package com.wtf.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * desc:
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 3/11/2020
 */
@Component
@Slf4j
public class TokenValidFilter implements GlobalFilter, Ordered {

    private static final String MODULE_EMAIL = "email";

    public static final String URL_LOGIN = "login";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String uriPath = request.getURI().getPath();

        //登录参数合法性校验，这里为了方便，只校验用户名的长度不能超过30
        if (uriPath.contains(URL_LOGIN)) {
            String username = uriPath.substring(URL_LOGIN.length() + 1, uriPath.lastIndexOf("/"));
            if (username.length() > 30) {
                response.setStatusCode(HttpStatus.OK);
                DataBuffer wrap = response.bufferFactory().wrap("用户名或者密码不合法".getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }

        // 按照要求，只校验email模块
        if (uriPath.contains(MODULE_EMAIL)) {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            List<HttpCookie> token = cookies.get("token");
            //这里我们只校验token是否为空
            if (token == null || token.size() <= 0) {
                response.setStatusCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION);
                DataBuffer wrap = response.bufferFactory().wrap("permission dion".getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
